package ynu.edu.elmservlet.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import ynu.edu.elmservlet.po.DeliveryAddress;
import ynu.edu.elmservlet.service.DeliveryAddressService;
import ynu.edu.elmservlet.service.impl.DeliveryAddressServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DeliveryAddressController extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();

    private Map<String, Object> getRequestData(HttpServletRequest request) throws IOException {
        String contentType = request.getContentType();
        Map<String, Object> data = new HashMap<>();
        
        try {
            if (contentType != null && contentType.contains("application/x-www-form-urlencoded")) {
                // 处理 form 数据
                Map<String, String[]> parameterMap = request.getParameterMap();
                for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                    if (entry.getValue() != null && entry.getValue().length > 0) {
                        data.put(entry.getKey(), entry.getValue()[0]);
                    }
                }
                
                // 如果参数为空，尝试从请求体读取
                if (data.isEmpty()) {
                    BufferedReader reader = request.getReader();
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    String body = sb.toString();
                    System.out.println("Request body: " + body); // 添加调试日志
                    
                    // 解析 URL 编码的表单数据
                    String[] pairs = body.split("&");
                    for (String pair : pairs) {
                        String[] keyValue = pair.split("=");
                        if (keyValue.length == 2) {
                            String key = java.net.URLDecoder.decode(keyValue[0], "UTF-8");
                            String value = java.net.URLDecoder.decode(keyValue[1], "UTF-8");
                            data.put(key, value);
                        }
                    }
                }
            } else {
                // 处理 JSON 数据
                BufferedReader reader = request.getReader();
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                String jsonStr = sb.toString();
                System.out.println("JSON data: " + jsonStr); // 添加调试日志
                
                if (!jsonStr.isEmpty()) {
                    Map<String, Object> jsonData = objectMapper.readValue(jsonStr, Map.class);
                    data.putAll(jsonData);
                }
            }
            
            System.out.println("Parsed data: " + data); // 添加调试日志
            return data;
        } catch (Exception e) {
            System.out.println("Parse request data error: " + e.getMessage()); // 添加调试日志
            e.printStackTrace();
            throw e;
        }
    }

    private void writeValue(Object obj, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        objectMapper.writeValue(response.getOutputStream(), obj);
    }

    public Object listDeliveryAddressByUserId(HttpServletRequest request) throws Exception{
        String userId = request.getParameter("userId");
        DeliveryAddressService service = new DeliveryAddressServiceImpl();
        List<DeliveryAddress> list= service.listDeliveryAddressByUserId(userId);
        return list;
    }

    public Object saveDeliveryAddress(HttpServletRequest request) throws Exception{
        DeliveryAddress deliveryAddress = new DeliveryAddress();
        deliveryAddress.setContactName(request.getParameter("contactName"));
        deliveryAddress.setContactSex(Integer.valueOf(request.getParameter("contactSex")));
        deliveryAddress.setContactTel(request.getParameter("contactTel"));
        deliveryAddress.setAddress(request.getParameter("address"));
        deliveryAddress.setUserId(request.getParameter("userId"));
        DeliveryAddressService service = new DeliveryAddressServiceImpl();
        int result = service.saveDeliveryAddress(deliveryAddress);
        return result;
    }

    public Object getDeliveryAddressById(HttpServletRequest request) throws Exception{
        Integer daId = Integer.valueOf(request.getParameter("daId"));
        DeliveryAddressService service = new DeliveryAddressServiceImpl();
        DeliveryAddress deliveryAddress = service.getDeliveryAddressById(daId);
        return deliveryAddress;
    }

    public Object updateDeliveryAddress(HttpServletRequest request) throws Exception {
        try {
            // 从请求体中获取数据
            Map<String, Object> requestData = getRequestData(request);
            System.out.println("Received data: " + requestData); // 添加调试日志
            
            DeliveryAddress deliveryAddress = new DeliveryAddress();
            deliveryAddress.setDaId(Integer.valueOf(String.valueOf(requestData.get("daId"))));
            deliveryAddress.setContactName(String.valueOf(requestData.get("contactName")));
            deliveryAddress.setContactSex(Integer.valueOf(String.valueOf(requestData.get("contactSex"))));
            deliveryAddress.setContactTel(String.valueOf(requestData.get("contactTel")));
            deliveryAddress.setAddress(String.valueOf(requestData.get("address")));
            
            System.out.println("Parsed address: " + deliveryAddress); // 添加调试日志
            
            DeliveryAddressService service = new DeliveryAddressServiceImpl();
            int result = service.updateDeliveryAddress(deliveryAddress);
            System.out.println("Update result: " + result); // 添加调试日志
            return result;
        } catch (Exception e) {
            System.out.println("Update error: " + e.getMessage()); // 添加调试日志
            e.printStackTrace();
            throw e;
        }
    }

    public Object removeDeliveryAddress(HttpServletRequest request) throws Exception{
        Integer daId = Integer.valueOf(request.getParameter("daId"));
        DeliveryAddressService service = new DeliveryAddressServiceImpl();
        int result = service.removeDeliveryAddress(daId);
        return result;
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1);
        
        try {
            if ("updateDeliveryAddress".equals(op)) {
                writeValue(updateDeliveryAddress(request), response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1);
        
        try {
            if ("listDeliveryAddressByUserId".equals(op)) {
                writeValue(listDeliveryAddressByUserId(request), response);
            } else if ("getDeliveryAddressById".equals(op)) {
                writeValue(getDeliveryAddressById(request), response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1);
        
        try {
            if ("saveDeliveryAddress".equals(op)) {
                writeValue(saveDeliveryAddress(request), response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1);
        
        try {
            if ("removeDeliveryAddress".equals(op)) {
                writeValue(removeDeliveryAddress(request), response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}